<template>
  <div class="search">
    <!-- 1.0 头部搜索框 -->
    <div class="header">
      <van-search
        v-model.trim="keyword"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #left>
          <i @click="$router.back()" class="iconfont iconjiantou"></i>
        </template>
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>
    <!-- 2.0 历史记录和热门搜索 -->
    <div class="group" v-show="!searchList.length">
      <h3 class="title">历史记录</h3>
      <div class="list">
        <span class="item" v-for="(item, index) in setHistory" :key="index" @click="btnFn(item)">{{
          item
        }}</span>
      </div>
    </div>
    <van-empty description="还没有搜索" v-show="!setHistory.length" />
    <!-- 3.0 搜索结果面板 -->
    <div class="result" v-show="searchList.length">
      <router-link
        class="item"
        v-for="item in searchList"
        :key="item.id"
        :to="`/aritcle/${item.id}`"
      >
        <span class="text">{{ item.title }}</span>
        <i class="iconfont iconjiantou1"></i>
      </router-link>
    </div>
  </div>
</template>

<script>
import { postSearchAPI } from "../apis/news.js";
import { setHistorySearch, getHistorySearch } from "../utils/tokenData.js";
export default {
  data() {
    return {
      keyword: "",
      searchList: [],
      setHistory: getHistorySearch(),
    };
  },
  methods: {
    async onSearch() {
      console.log("点击了搜索按钮", this.keyword);
      const res = await postSearchAPI({ keyword: this.keyword });
      if (!res.data.data.length) {
        this.$toast("没有搜索到相关东西");
      } else {
        //把搜索词加到历史记录
        this.setHistory.push(this.keyword);
        //去重
        this.setHistory = [...new Set(this.setHistory)];
        
        this.searchList = res.data.data;
      }
    },
    btnFn(item){
      this.keyword = item
     this.onSearch()
    }
  },
  watch: {
    keyword() {
      if (this.keyword == "") {
        this.searchList = [];
      }
    },
    setHistory() {
      setHistorySearch(this.setHistory);
    },
  },
};
</script>

<style lang="less" scoped>
.group {
  padding: 10px;
  .title {
    font-size: 16px;
    margin: 10px 0;
  }

  .list {
    display: flex;
    flex-wrap: wrap;
    .item {
      padding: 5px;
      font-size: 13px;
      margin-right: 10px;
      border: 1px solid #ccc;
    }
  }
}
.result {
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    border-bottom: 1px solid #ccc;
  }
}
</style>